"""
岗位管理视图
"""
from rest_framework import generics, status, filters
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from django.utils import timezone
from django.db.models import Q
from accounts.permissions import IsTeacherOrAdmin
from students.models import Student
from .models import Company, Job, JobApplication
from .serializers import (
    CompanySerializer, CompanyListSerializer,
    JobSerializer, JobListSerializer, JobCreateSerializer,
    JobApplicationSerializer, JobApplicationListSerializer,
    MyJobApplicationSerializer
)


class CompanyListCreateView(generics.ListCreateAPIView):
    """公司列表和创建"""
    permission_classes = [IsTeacherOrAdmin]
    queryset = Company.objects.all()
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    search_fields = ['name', 'industry', 'address']
    filterset_fields = ['company_type', 'company_size', 'industry']

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return CompanyListSerializer
        return CompanySerializer


class CompanyDetailView(generics.RetrieveUpdateDestroyAPIView):
    """公司详情"""
    permission_classes = [IsTeacherOrAdmin]
    queryset = Company.objects.all()
    serializer_class = CompanySerializer


class JobListCreateView(generics.ListCreateAPIView):
    """岗位列表和创建"""
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    search_fields = ['title', 'company__name', 'work_location', 'description']
    filterset_fields = ['job_type', 'work_mode', 'status', 'company', 'is_featured']

    def get_queryset(self):
        """根据用户角色返回不同的查询集"""
        user = self.request.user
        queryset = Job.objects.select_related('company', 'published_by')

        if user.role == 'student':
            # 学生只能看到已发布的岗位
            queryset = queryset.filter(status='published')

            # 添加薪资范围搜索
            salary_min = self.request.query_params.get('salary_min')
            salary_max = self.request.query_params.get('salary_max')
            if salary_min:
                queryset = queryset.filter(
                    Q(salary_min__gte=salary_min) | Q(salary_negotiable=True)
                )
            if salary_max:
                queryset = queryset.filter(
                    Q(salary_max__lte=salary_max) | Q(salary_negotiable=True)
                )

        return queryset.order_by('-created_at')

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return JobListSerializer
        return JobCreateSerializer

    def perform_create(self, serializer):
        """创建岗位时设置发布人"""
        serializer.save(published_by=self.request.user)


class JobDetailView(generics.RetrieveUpdateDestroyAPIView):
    """岗位详情"""
    permission_classes = [IsAuthenticated]
    queryset = Job.objects.select_related('company', 'published_by')
    serializer_class = JobSerializer

    def get_permissions(self):
        """根据操作类型设置权限"""
        if self.request.method in ['PUT', 'PATCH', 'DELETE']:
            # 只有管理员和老师可以编辑/删除
            permission_classes = [IsTeacherOrAdmin]
        else:
            # 所有认证用户都可以查看
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes]


class JobApplicationListView(generics.ListAPIView):
    """岗位申请列表"""
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    search_fields = ['job__title', 'job__company__name', 'student__name', 'student__student_id']
    filterset_fields = ['status', 'job', 'student']

    def get_queryset(self):
        """根据用户角色返回不同的查询集"""
        user = self.request.user
        queryset = JobApplication.objects.select_related('job', 'job__company', 'student', 'reviewed_by')

        if user.role == 'student':
            # 学生只能看到自己的申请
            try:
                student = Student.objects.get(user=user)
                queryset = queryset.filter(student=student)
            except Student.DoesNotExist:
                queryset = queryset.none()

        return queryset.order_by('-applied_at')

    def get_serializer_class(self):
        user = self.request.user
        if user.role == 'student':
            return MyJobApplicationSerializer
        return JobApplicationListSerializer


class JobApplicationDetailView(generics.RetrieveUpdateDestroyAPIView):
    """岗位申请详情"""
    permission_classes = [IsAuthenticated]
    queryset = JobApplication.objects.select_related('job', 'job__company', 'student', 'reviewed_by')
    serializer_class = JobApplicationSerializer

    def get_queryset(self):
        """根据用户角色返回不同的查询集"""
        user = self.request.user
        queryset = super().get_queryset()

        if user.role == 'student':
            # 学生只能看到自己的申请
            try:
                student = Student.objects.get(user=user)
                queryset = queryset.filter(student=student)
            except Student.DoesNotExist:
                queryset = queryset.none()

        return queryset


class JobRecommendationListView(generics.ListAPIView):
    """岗位推荐列表"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
        return Response({'message': '岗位推荐列表接口开发中'})


@api_view(['POST'])
@permission_classes([IsTeacherOrAdmin])
def publish_job(request, pk):
    """发布岗位"""
    try:
        job = Job.objects.get(pk=pk)
        job.status = 'published'
        job.published_at = timezone.now()
        job.save()

        serializer = JobSerializer(job)
        return Response({
            'message': '岗位发布成功',
            'data': serializer.data
        })
    except Job.DoesNotExist:
        return Response(
            {'error': '岗位不存在'},
            status=status.HTTP_404_NOT_FOUND
        )


@api_view(['POST'])
@permission_classes([IsTeacherOrAdmin])
def close_job(request, pk):
    """关闭岗位"""
    try:
        job = Job.objects.get(pk=pk)
        job.status = 'closed'
        job.save()

        serializer = JobSerializer(job)
        return Response({
            'message': '岗位关闭成功',
            'data': serializer.data
        })
    except Job.DoesNotExist:
        return Response(
            {'error': '岗位不存在'},
            status=status.HTTP_404_NOT_FOUND
        )


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def apply_job(request, job_id):
    """申请岗位"""
    try:
        # 检查用户是否为学生
        if request.user.role != 'student':
            return Response(
                {'error': '只有学生可以申请岗位'},
                status=status.HTTP_403_FORBIDDEN
            )

        # 获取学生信息
        try:
            student = Student.objects.get(user=request.user)
        except Student.DoesNotExist:
            return Response(
                {'error': '学生信息不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

        # 获取岗位信息
        try:
            job = Job.objects.get(pk=job_id)
        except Job.DoesNotExist:
            return Response(
                {'error': '岗位不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

        # 检查岗位状态
        if job.status != 'published':
            return Response(
                {'error': '该岗位未发布或已关闭'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 检查是否已经申请过
        if JobApplication.objects.filter(job=job, student=student).exists():
            return Response(
                {'error': '您已经申请过该岗位'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 创建申请记录
        application_data = {
            'job': job.id,
            'student': student.id,
            'cover_letter': request.data.get('cover_letter', ''),
            'resume_file': request.data.get('resume_file')
        }

        serializer = JobApplicationSerializer(data=application_data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'message': '申请提交成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)
        else:
            return Response(
                {'error': serializer.errors},
                status=status.HTTP_400_BAD_REQUEST
            )

    except Exception as e:
        return Response(
            {'error': str(e)},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['POST'])
@permission_classes([IsTeacherOrAdmin])
def review_application(request, pk):
    """审核岗位申请"""
    try:
        application = JobApplication.objects.get(pk=pk)

        # 检查申请状态是否可以审核
        if application.status not in ['pending', 'reviewing']:
            return Response(
                {'error': '该申请已经审核过，无法重复审核'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 更新申请状态
        new_status = request.data.get('status')
        review_comments = request.data.get('review_comments', '')

        if new_status not in ['approved', 'rejected']:
            return Response(
                {'error': '无效的审核状态'},
                status=status.HTTP_400_BAD_REQUEST
            )

        application.status = new_status
        application.review_comments = review_comments
        application.reviewed_by = request.user
        application.reviewed_at = timezone.now()
        application.save()

        serializer = JobApplicationSerializer(application)
        return Response({
            'message': '审核完成',
            'data': serializer.data
        })

    except JobApplication.DoesNotExist:
        return Response(
            {'error': '申请记录不存在'},
            status=status.HTTP_404_NOT_FOUND
        )
    except Exception as e:
        return Response(
            {'error': str(e)},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


class JobRecommendationListView(generics.ListAPIView):
    """岗位推荐列表"""
    permission_classes = [IsAuthenticated]
    serializer_class = JobListSerializer

    def get_queryset(self):
        """获取推荐岗位"""
        # 只返回已发布且推荐的岗位
        return Job.objects.filter(
            status='published',
            is_featured=True
        ).select_related('company', 'published_by').order_by('-created_at')


@api_view(['POST'])
@permission_classes([IsTeacherOrAdmin])
def generate_recommendations(request):
    """生成岗位推荐"""
    # 这里可以实现智能推荐算法
    # 暂时返回简单的响应
    return Response({'message': '推荐生成功能开发中'})


@api_view(['GET'])
@permission_classes([IsTeacherOrAdmin])
def job_statistics(request):
    """岗位统计"""
    try:
        from django.db.models import Count, Q
        from datetime import datetime, timedelta
        from django.utils import timezone

        # 基本统计
        total_jobs = Job.objects.count()
        published_jobs = Job.objects.filter(status='published').count()
        draft_jobs = Job.objects.filter(status='draft').count()
        closed_jobs = Job.objects.filter(status='closed').count()
        expired_jobs = Job.objects.filter(status='expired').count()

        # 申请统计
        total_applications = JobApplication.objects.count()
        pending_applications = JobApplication.objects.filter(status='pending').count()
        approved_applications = JobApplication.objects.filter(status='approved').count()
        rejected_applications = JobApplication.objects.filter(status='rejected').count()

        # 公司统计
        total_companies = Company.objects.count()

        # 岗位类型统计
        job_type_stats = Job.objects.values('job_type').annotate(
            count=Count('id')
        ).order_by('-count')

        # 工作模式统计
        work_mode_stats = Job.objects.values('work_mode').annotate(
            count=Count('id')
        ).order_by('-count')

        # 公司类型统计
        company_type_stats = Company.objects.values('company_type').annotate(
            count=Count('id')
        ).order_by('-count')

        # 公司规模统计
        company_size_stats = Company.objects.values('company_size').annotate(
            count=Count('id')
        ).order_by('-count')

        # 行业统计
        industry_stats = Company.objects.values('industry').annotate(
            count=Count('id')
        ).order_by('-count')

        # 最近30天的趋势统计
        thirty_days_ago = timezone.now() - timedelta(days=30)
        recent_jobs = Job.objects.filter(created_at__gte=thirty_days_ago).count()
        recent_applications = JobApplication.objects.filter(applied_at__gte=thirty_days_ago).count()

        # 热门岗位（申请数量最多的前10个）
        popular_jobs = Job.objects.annotate(
            application_count=Count('jobapplication')
        ).order_by('-application_count')[:10].values(
            'id', 'title', 'company__name', 'application_count'
        )

        # 活跃公司（发布岗位最多的前10个）
        active_companies = Company.objects.annotate(
            job_count=Count('job')
        ).order_by('-job_count')[:10].values(
            'id', 'name', 'company_type', 'job_count'
        )

        statistics = {
            'jobs': {
                'total': total_jobs,
                'published': published_jobs,
                'draft': draft_jobs,
                'closed': closed_jobs,
                'expired': expired_jobs,
                'recent_30_days': recent_jobs
            },
            'applications': {
                'total': total_applications,
                'pending': pending_applications,
                'approved': approved_applications,
                'rejected': rejected_applications,
                'recent_30_days': recent_applications,
                'success_rate': round((approved_applications / total_applications * 100), 2) if total_applications > 0 else 0
            },
            'companies': {
                'total': total_companies,
                'active_companies': list(active_companies)
            },
            'job_types': list(job_type_stats),
            'work_modes': list(work_mode_stats),
            'company_types': list(company_type_stats),
            'company_sizes': list(company_size_stats),
            'industries': list(industry_stats),
            'popular_jobs': list(popular_jobs)
        }

        return Response({
            'message': '统计数据获取成功',
            'data': statistics
        })

    except Exception as e:
        return Response(
            {'error': str(e)},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )





@api_view(['GET'])
@permission_classes([IsTeacherOrAdmin])
def detailed_job_statistics(request):
    """详细岗位统计"""
    try:
        from django.db.models import Count, Q, Avg
        from datetime import datetime, timedelta
        from django.utils import timezone

        # 获取查询参数
        period = request.GET.get('period', 'month')  # week, month, quarter, year

        # 计算时间范围
        now = timezone.now()
        if period == 'week':
            start_date = now - timedelta(days=7)
        elif period == 'month':
            start_date = now - timedelta(days=30)
        elif period == 'quarter':
            start_date = now - timedelta(days=90)
        else:  # year
            start_date = now - timedelta(days=365)

        # 时间段内的统计
        period_jobs = Job.objects.filter(created_at__gte=start_date)
        period_applications = JobApplication.objects.filter(applied_at__gte=start_date)

        # 岗位发布趋势（按天统计）
        job_trends = []
        for i in range(30):  # 最近30天
            date = (now - timedelta(days=i)).date()
            count = Job.objects.filter(created_at__date=date).count()
            job_trends.append({
                'date': date.strftime('%Y-%m-%d'),
                'count': count
            })
        job_trends.reverse()

        # 申请趋势（按天统计）
        application_trends = []
        for i in range(30):  # 最近30天
            date = (now - timedelta(days=i)).date()
            count = JobApplication.objects.filter(applied_at__date=date).count()
            application_trends.append({
                'date': date.strftime('%Y-%m-%d'),
                'count': count
            })
        application_trends.reverse()

        # 薪资分布统计
        salary_ranges = [
            {'range': '3000以下', 'min': 0, 'max': 3000},
            {'range': '3000-5000', 'min': 3000, 'max': 5000},
            {'range': '5000-8000', 'min': 5000, 'max': 8000},
            {'range': '8000-12000', 'min': 8000, 'max': 12000},
            {'range': '12000-20000', 'min': 12000, 'max': 20000},
            {'range': '20000以上', 'min': 20000, 'max': 999999}
        ]

        salary_distribution = []
        for salary_range in salary_ranges:
            count = Job.objects.filter(
                salary_min__gte=salary_range['min'],
                salary_max__lte=salary_range['max']
            ).count()
            salary_distribution.append({
                'range': salary_range['range'],
                'count': count
            })

        # 地区分布统计
        location_stats = Job.objects.values('work_location').annotate(
            count=Count('id')
        ).order_by('-count')[:10]

        # 学历要求统计
        education_stats = Job.objects.values('education_requirement').annotate(
            count=Count('id')
        ).order_by('-count')

        # 经验要求统计
        experience_stats = Job.objects.values('experience_requirement').annotate(
            count=Count('id')
        ).order_by('-count')

        # 申请成功率分析（按岗位类型）
        job_type_success_rates = []
        for job_type_stat in Job.objects.values('job_type').annotate(count=Count('id')):
            job_type = job_type_stat['job_type']
            total_apps = JobApplication.objects.filter(job__job_type=job_type).count()
            approved_apps = JobApplication.objects.filter(
                job__job_type=job_type,
                status='approved'
            ).count()
            success_rate = (approved_apps / total_apps * 100) if total_apps > 0 else 0

            job_type_success_rates.append({
                'job_type': job_type,
                'total_applications': total_apps,
                'approved_applications': approved_apps,
                'success_rate': round(success_rate, 2)
            })

        # 公司招聘活跃度
        company_activity = Company.objects.annotate(
            total_jobs=Count('job'),
            active_jobs=Count('job', filter=Q(job__status='published')),
            total_applications=Count('job__jobapplication')
        ).order_by('-total_jobs')[:20]

        company_activity_data = []
        for company in company_activity:
            company_activity_data.append({
                'id': company.id,
                'name': company.name,
                'company_type': company.company_type,
                'total_jobs': company.total_jobs,
                'active_jobs': company.active_jobs,
                'total_applications': company.total_applications
            })

        detailed_stats = {
            'period_summary': {
                'period': period,
                'start_date': start_date.strftime('%Y-%m-%d'),
                'end_date': now.strftime('%Y-%m-%d'),
                'jobs_created': period_jobs.count(),
                'applications_submitted': period_applications.count()
            },
            'trends': {
                'job_publication': job_trends,
                'job_applications': application_trends
            },
            'distributions': {
                'salary': salary_distribution,
                'location': list(location_stats),
                'education': list(education_stats),
                'experience': list(experience_stats)
            },
            'success_rates': {
                'by_job_type': job_type_success_rates
            },
            'company_activity': company_activity_data
        }

        return Response({
            'message': '详细统计数据获取成功',
            'data': detailed_stats
        })

    except Exception as e:
        return Response(
            {'error': str(e)},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['POST'])
@permission_classes([IsTeacherOrAdmin])
def generate_recommendations(request):
    """生成推荐"""
    return Response({'message': '生成推荐接口开发中'})
